package com.base.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.homework.entity.User;
import com.homework.service.UserService;



/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name=request.getParameter("uname");
		String pwd=request.getParameter("password");
		System.out.println("前端传过来的用户名是："+name);
		System.out.println("前端传过来的用户名是："+pwd);
		UserService us=new UserService();
		User user=us.login(name, pwd);
		String path="fail.html";
		
		if(user!=null){
			path="index.jsp";
			
			//把成功登陆的用户名，存入session
			HttpSession session=request.getSession();
			session.setAttribute("uname", name);
			session.setAttribute("loginuser", user);
		}
		
		Map rsmap=new HashMap();
		rsmap.put("result", path);
		//对象，转json格式字符串
		String rs1=JSONObject.toJSONString(rsmap);
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().append(rs1);
		/**
		 * 1. 请求转发：
　　　　(1) 使用requestDispatcher对象：

　　　　　　转发格式：request.getRequestDispatcher("path").forward(response,request)

　　　　(2) 使用jsp动作元素：

　　　　　　<jsp:forward page=""/>

　　2. 请求重定向：
　　　　使用response的rsendRedirect方法：

　　　　　　重定向格式：response.sendRedirect("path");
		 */
//		response.sendRedirect(path);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
